package nacos

import (
	"strconv"
	"strings"

	"gitee.com/fanshuaiself/wss-gateway/constants"
	"gitee.com/fanshuaiself/wss-gateway/util"
	"github.com/nacos-group/nacos-sdk-go/clients"
	"github.com/nacos-group/nacos-sdk-go/clients/config_client"
	"github.com/nacos-group/nacos-sdk-go/clients/naming_client"
	"github.com/nacos-group/nacos-sdk-go/common/constant"
	"github.com/nacos-group/nacos-sdk-go/model"
	"github.com/nacos-group/nacos-sdk-go/vo"

	log "github.com/sirupsen/logrus"
)

type nacosClient struct{
	Ip string 
	Port int 
	NacosServerAddr string 
	NacosServerPort int 
	NacosServiceName string 
	NacosServiceGroup string 
	namingClient naming_client.INamingClient
	configClient config_client.IConfigClient
}

func newClient(config *constants.Config) *nacosClient {
	arr := strings.Split(config.NacosServer, ":")
	port, _ := strconv.Atoi(arr[1])
	client := &nacosClient{
		Ip: util.GetIp(),
		Port: 8080,
		NacosServerAddr: arr[0],
		NacosServerPort: port,
		NacosServiceName: config.NacosServiceName,
		NacosServiceGroup: config.NacosServiceGroup,
	}

	clientConfig := constant.ClientConfig{
		NamespaceId: "",
		LogDir: "/tmp/nacos/log",
		CacheDir: "/tmp/nacos/cache",
	}
	serverConfig := constant.ServerConfig{
		IpAddr: client.Ip,
		Port: uint64(client.Port),
		ContextPath: "/nacos",
		Scheme: "http",
	}
	clientParam := vo.NacosClientParam{
		ClientConfig: &clientConfig,
		ServerConfigs: []constant.ServerConfig{serverConfig},
	}
	namingClient, err := clients.NewNamingClient(clientParam)
	if err != nil {
		log.Fatal(err)
	}
	client.namingClient = namingClient

	configClient, err := clients.NewConfigClient(clientParam)
	if err != nil {
		log.Fatal(err)
	}
	client.configClient = configClient

	return client
}

func (c *nacosClient) Redister(up bool) {
	instanceParam := vo.RegisterInstanceParam{
		ServiceName: c.NacosServiceName,
		Ip: c.Ip,
		Port: uint64(c.Port),
		Enable: up,
		Healthy: up,
		Weight: 100,
		Metadata: map[string]string{},
		Ephemeral: true,
	}
	instanceParam.Metadata["group"] = c.NacosServiceGroup

	c.namingClient.RegisterInstance(instanceParam)
}

func (c *nacosClient) Deregister() {
	c.namingClient.DeregisterInstance(vo.DeregisterInstanceParam{
		ServiceName: c.NacosServiceName,
		Ip: c.Ip,
		Port: uint64(c.Port),
		Ephemeral: true,
	})
}

func (c *nacosClient) GetAllServices() map[string]model.Service {
	serviceList, err := c.namingClient.GetAllServicesInfo(vo.GetAllServiceInfoParam{
		PageNo: 1,
		PageSize: 500,
	}) 

	services := make(map[string]model.Service)
	if err == nil {
		for _, serviceName := range serviceList.Doms {
			service, err1 := c.namingClient.GetService(vo.GetServiceParam{
				ServiceName: serviceName,
			})
			if err1 == nil {
				services[serviceName] = service
			}
		}
	}
	return services
}

func (c *nacosClient) GetConfig(dataId, groupId string) (string, error) {
	return c.configClient.GetConfig(vo.ConfigParam{
		DataId: dataId,
		Group: groupId,
	})
}